#include "threadpool.h"
#include <stdio.h>
#include <iostream>

// 初始化
ThreadPool::ThreadPool() 
    : poolSize_(0)
{
    pthread_mutex_init(&queMutex_, NULL);
    pthread_cond_init(&queCond_, NULL);
}

// 释放资源
ThreadPool::~ThreadPool()
{
    pthread_mutex_destroy(&queMutex_);
    pthread_cond_destroy(&queCond_);
}

// 启动线程池，用户可以通过参数指定线程个数，默认为1个线程
void ThreadPool::startPool(int threadNum)
{
    poolSize_ = threadNum;

    // 创建线程对象，放入list
    for (int i=0; i < poolSize_; i++)
    {
        threadLists_.push_back(make_shared<Thread>(this)); // ThreadPool*
    }

    // 启动线程
    for (auto it = threadLists_.begin(); it != threadLists_.end(); ++it)
    {
        // (*it) Thread*
        (*it)->start();
    }
}

// 提交任务到线程池分配线程执行
void ThreadPool::submit(weak_ptr<Task> wp)
{
    pthread_mutex_lock(&queMutex_);
    taskQue_.push(wp);
    pthread_mutex_unlock(&queMutex_);
    pthread_cond_broadcast(&queCond_);
}